<template>
  <div class="home-dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <div class="welcome-text">
          <h1>欢迎回来，{{ currentUser?.name || currentUser?.username || '用户' }}！</h1>
          <p class="welcome-subtitle">{{ getWelcomeMessage() }}</p>
          <div class="quick-stats">
            <div class="stat-item">
              <span class="stat-icon">📊</span>
              <span class="stat-text">今日登录：{{ formatTime(new Date()) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-icon">🏢</span>
              <span class="stat-text">部门：{{ currentUser?.department || '未设置' }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-icon">👔</span>
              <span class="stat-text">职位：{{ currentUser?.position || '未设置' }}</span>
            </div>
          </div>
        </div>
        <div class="welcome-avatar">
          <div class="avatar-container">
            <img v-if="currentUser?.avatarUrl" :src="currentUser.avatarUrl" :alt="currentUser.name" />
            <div v-else class="avatar-placeholder">
              {{ (currentUser?.name || currentUser?.username || 'U').charAt(0) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷功能区 -->
    <div class="quick-actions-section">
      <h2>快捷功能</h2>
      <div class="action-grid">
        <!-- 财务管理快捷入口 -->
        <div class="action-card finance" @click="navigateTo('/finance')">
          <div class="card-icon">💰</div>
          <div class="card-content">
            <h3>财务管理</h3>
            <p>应收应付、对账报表</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 个人信息 -->
        <div class="action-card profile" @click="navigateTo('/system/profile')">
          <div class="card-icon">👤</div>
          <div class="card-content">
            <h3>个人信息</h3>
            <p>完善个人资料</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 修改密码 -->
        <div class="action-card security" @click="navigateTo('/system/change-password')">
          <div class="card-icon">🔒</div>
          <div class="card-content">
            <h3>修改密码</h3>
            <p>提高账户安全</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 商品管理 -->
        <div class="action-card commodity" @click="navigateTo('/commodity')">
          <div class="card-icon">📦</div>
          <div class="card-content">
            <h3>商品管理</h3>
            <p>商品分类、库存</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 采购管理 -->
        <div class="action-card procure" @click="navigateTo('/procure')">
          <div class="card-icon">🛒</div>
          <div class="card-content">
            <h3>采购管理</h3>
            <p>采购订单、供应商</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 销售管理 -->
        <div class="action-card sales" @click="navigateTo('/sales')">
          <div class="card-icon">📈</div>
          <div class="card-content">
            <h3>销售管理</h3>
            <p>销售订单、客户</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 仓库管理 -->
        <div class="action-card warehouse" @click="navigateTo('/ware')">
          <div class="card-icon">🏭</div>
          <div class="card-content">
            <h3>仓库管理</h3>
            <p>出入库、库存管理</p>
          </div>
          <div class="card-arrow">→</div>
        </div>

        <!-- 零售管理 -->
        <div class="action-card retail" @click="navigateTo('/retail')">
          <div class="card-icon">🛍️</div>
          <div class="card-content">
            <h3>零售管理</h3>
            <p>零售订单、客户管理</p>
          </div>
          <div class="card-arrow">→</div>
        </div>
      </div>
    </div>

    <!-- 财务数据概览 -->
    <div class="finance-overview-section">
      <h2>财务概览</h2>
      <div class="overview-grid">
        <div class="overview-card receivable">
          <div class="card-header">
            <span class="card-title">应收账款</span>
            <span class="card-icon">📊</span>
          </div>
          <div class="card-value">¥ {{ formatCurrency(financeData.receivableAmount) }}</div>
          <div class="card-subtitle">待收款金额</div>
          <div class="card-action" @click="navigateTo('/finance/accounts-receivable')">
            查看详情 →
          </div>
        </div>

        <div class="overview-card payable">
          <div class="card-header">
            <span class="card-title">应付账款</span>
            <span class="card-icon">💳</span>
          </div>
          <div class="card-value">¥ {{ formatCurrency(financeData.payableAmount) }}</div>
          <div class="card-subtitle">待付款金额</div>
          <div class="card-action" @click="navigateTo('/finance/accounts-payable')">
            查看详情 →
          </div>
        </div>

        <div class="overview-card payment">
          <div class="card-header">
            <span class="card-title">付款记录</span>
            <span class="card-icon">💰</span>
          </div>
          <div class="card-value">{{ financeData.paymentCount }} 笔</div>
          <div class="card-subtitle">本月付款记录</div>
          <div class="card-action" @click="navigateTo('/finance/payment-record')">
            查看详情 →
          </div>
        </div>

        <div class="overview-card collection">
          <div class="card-header">
            <span class="card-title">收款记录</span>
            <span class="card-icon">💎</span>
          </div>
          <div class="card-value">{{ financeData.collectionCount }} 笔</div>
          <div class="card-subtitle">本月收款记录</div>
          <div class="card-action" @click="navigateTo('/finance/collection-record')">
            查看详情 →
          </div>
        </div>
      </div>
    </div>

    <!-- 系统公告/帮助 -->
    <div class="announcement-section">
      <h2>系统公告</h2>
      <div class="announcement-card">
        <div class="announcement-header">
          <span class="announcement-title">📢 系统更新通知</span>
          <span class="announcement-date">{{ formatDate(new Date()) }}</span>
        </div>
        <div class="announcement-content">
          <p>✅ 财务管理模块已完成：应收应付管理、对账功能、Excel导出</p>
          <p>✅ 零售管理模块已完成：零售订单管理、客户管理、销售统计</p>
          <p>💡 建议：首次登录后请完善个人信息并修改密码提高安全性</p>
        </div>
      </div>

      <div class="help-card">
        <div class="help-header">
          <span class="help-title">💡 使用帮助</span>
        </div>
        <div class="help-content">
          <div class="help-item">
            <span class="help-icon">📊</span>
            <span class="help-text">财务报表支持筛选和Excel导出功能</span>
          </div>
          <div class="help-item">
            <span class="help-icon">🔒</span>
            <span class="help-text">建议定期修改密码，使用强密码提高安全性</span>
          </div>
          <div class="help-item">
            <span class="help-icon">🛍️</span>
            <span class="help-text">零售管理支持订单跟踪、客户分析和销售报表</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, apiGet } from '../../utils/api.js'

const router = useRouter()
const currentUser = ref(null)
const financeData = ref({
  receivableAmount: 0,
  payableAmount: 0,
  paymentCount: 0,
  collectionCount: 0
})

onMounted(async () => {
  // 先获取本地用户信息
  currentUser.value = getCurrentUser()
  
  // 然后从后端获取最新的详细信息
  try {
    let userId = currentUser.value?.id
    let response
    
    if (userId) {
      response = await apiGet(`/system/user/profile/${userId}`)
    } else if (currentUser.value?.username) {
      response = await apiGet(`/system/user/profile/by-username?username=${encodeURIComponent(currentUser.value.username)}`)
      if (response?.id) {
        localStorage.setItem('userId', String(response.id))
      }
    }
    
    if (response) {
      // 更新用户信息，包括部门和职位
      currentUser.value = {
        ...currentUser.value,
        ...response
      }
      
      // 持久化最新信息
      if (response.name) localStorage.setItem('name', response.name)
      if (response.department) localStorage.setItem('department', response.department)
      if (response.position) localStorage.setItem('position', response.position)
      if (response.email) localStorage.setItem('email', response.email)
      if (response.avatarUrl) localStorage.setItem('avatarUrl', response.avatarUrl)
    }
  } catch (error) {
    console.error('获取用户详细信息失败:', error)
  }
  
  // 加载财务概览数据
  await loadFinanceData()
})

const loadFinanceData = async () => {
  try {
    // 获取财务仪表板数据
    const response = await apiGet('/finance/dashboard')
    if (response) {
      financeData.value = {
        receivableAmount: response.totalReceivable || 0,
        payableAmount: response.totalPayable || 0,
        paymentCount: response.monthlyPayment || 0,
        collectionCount: response.monthlyReceipt || 0
      }
    }
  } catch (error) {
    console.error('获取财务数据失败:', error)
    // 保持默认值
  }
}

const navigateTo = (path) => {
  router.push(path)
}

const getWelcomeMessage = () => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了，注意休息'
  if (hour < 9) return '早上好，新的一天开始了！'
  if (hour < 12) return '上午好，工作愉快！'
  if (hour < 14) return '中午好，记得午休'
  if (hour < 18) return '下午好，继续加油！'
  if (hour < 22) return '晚上好，今天辛苦了'
  return '夜深了，早点休息'
}

const formatTime = (date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDate = (date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const formatCurrency = (amount) => {
  if (amount === 0) return '0.00'
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(amount)
}
</script>

<style scoped>
.home-dashboard {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 欢迎区域 */
.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 32px;
  color: white;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 32px;
}

.welcome-text h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 600;
}

.welcome-subtitle {
  margin: 0 0 24px 0;
  font-size: 18px;
  opacity: 0.9;
}

.quick-stats {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
}

.stat-icon {
  font-size: 16px;
}

.welcome-avatar {
  flex-shrink: 0;
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid rgba(255, 255, 255, 0.2);
}

.avatar-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: 600;
}

/* 快捷功能区 */
.quick-actions-section, .finance-overview-section, .announcement-section {
  margin-bottom: 32px;
}

.quick-actions-section h2, .finance-overview-section h2, .announcement-section h2 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.action-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 16px;
  border: 2px solid transparent;
}

.action-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.action-card.finance:hover { border-color: #f39c12; }
.action-card.profile:hover { border-color: #3498db; }
.action-card.security:hover { border-color: #e74c3c; }
.action-card.commodity:hover { border-color: #9b59b6; }
.action-card.procure:hover { border-color: #2ecc71; }
.action-card.sales:hover { border-color: #e67e22; }
.action-card.warehouse:hover { border-color: #34495e; }
.action-card.retail:hover { border-color: #e91e63; }

.card-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  flex-shrink: 0;
}

.action-card.finance .card-icon { background: linear-gradient(135deg, #f39c12, #d68910); }
.action-card.profile .card-icon { background: linear-gradient(135deg, #3498db, #2980b9); }
.action-card.security .card-icon { background: linear-gradient(135deg, #e74c3c, #c0392b); }
.action-card.commodity .card-icon { background: linear-gradient(135deg, #9b59b6, #8e44ad); }
.action-card.procure .card-icon { background: linear-gradient(135deg, #2ecc71, #27ae60); }
.action-card.sales .card-icon { background: linear-gradient(135deg, #e67e22, #d35400); }
.action-card.warehouse .card-icon { background: linear-gradient(135deg, #34495e, #2c3e50); }
.action-card.retail .card-icon { background: linear-gradient(135deg, #e91e63, #c2185b); }

.card-content {
  flex: 1;
}

.card-content h3 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.card-content p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.card-arrow {
  font-size: 20px;
  color: #bdc3c7;
  font-weight: bold;
  transition: all 0.3s ease;
}

.action-card:hover .card-arrow {
  color: #2c3e50;
  transform: translateX(4px);
}

/* 财务概览 */
.overview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.card-header .card-icon {
  font-size: 20px;
}

.card-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 4px;
}

.overview-card.receivable .card-value { color: #2ecc71; }
.overview-card.payable .card-value { color: #e74c3c; }
.overview-card.payment .card-value { color: #3498db; }
.overview-card.collection .card-value { color: #f39c12; }

.card-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 16px;
}

.card-action {
  color: #667eea;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.card-action:hover {
  color: #5a67d8;
}

/* 公告区域 */
.announcement-card, .help-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.announcement-header, .help-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.announcement-title, .help-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.announcement-date {
  font-size: 14px;
  color: #7f8c8d;
}

.announcement-content p {
  margin: 8px 0;
  color: #4a5568;
  line-height: 1.6;
}

.help-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.help-item {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #4a5568;
}

.help-icon {
  font-size: 16px;
  width: 24px;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }
  
  .quick-stats {
    justify-content: center;
  }
  
  .action-grid, .overview-grid {
    grid-template-columns: 1fr;
  }
  
  .action-card {
    padding: 20px;
  }
  
  .welcome-text h1 {
    font-size: 24px;
  }
  
  .welcome-subtitle {
    font-size: 16px;
  }
}
</style>